package org.ehe.ai.controller;

import org.ehe.ai.websocket.ChatWebSocketHandler;
import org.ehe.common.core.domain.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * AI-websocket方法
 * @author :zhangnn
 * @className :ChatWebSocketController
 * @description: TODO
 * @date 2025-08-23 09:58:19
 */
@RestController
@RequestMapping("/chat/websocket")
@CrossOrigin(origins = "*")
public class ChatWebSocketController {
    @Autowired
    private ChatWebSocketHandler chatWebSocketHandler;

    /**
     * 获取WebSocket连接状态
     */
    @GetMapping("/status")
    public R<Map<String, Object>> getWebSocketStatus() {
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("activeConnections", chatWebSocketHandler.getActiveConnectionCount());
        result.put("endpoint", "/ws/chat/{sessionId}");
        return R.ok(result);
    }

    /**
     * 向指定会话广播消息
     */
    @PostMapping("/broadcast/{sessionId}")
    public R<Map<String, Object>> broadcastMessage(
        @PathVariable String sessionId,
        @RequestParam String type,
        @RequestParam String message) {

        Map<String, Object> result = new HashMap<>();

        try {
            chatWebSocketHandler.broadcastToSession(sessionId, type, message);
            result.put("success", true);
            result.put("message", "消息已广播");
            return R.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "广播失败: " + e.getMessage());
            return R.fail(result);
        }
    }
}
